import axios from 'axios'
import { message } from 'ant-design-vue'
import { getToken, refreshToken } from '@/utils/auth'
// import router from '@/router'

const service = axios.create({
  timeout: 5 * 60 * 1000,
  withCredentials: false
})

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    if (process.env.NODE_ENV === 'development') {
      config.url = '/api' + config.url
    }

    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const contentType = response.headers['content-type']
    if (contentType && contentType.indexOf('application/json') !== -1) {
      const code = response.data.code
      if (code !== undefined) {
        if (code === 0) {
          return response.data.data
        }
        // message.error(response.data.msg)
        // loginStore.getMsg(response.data.msg)
        return Promise.reject(response.data)
      }
      return response.data
    }
    return response
  },
  (error) => {
    if (error.response.status === 424) {
      refreshToken()
      return error.response.data
    }else{
      return Promise.reject(error)
    }

    // if (error.response.data.msg) {
    //   message.error(error.response.data.msg)
    // }
  }
)

export default service
